package com.itzyf.pokemondata.activity.rank

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.activity.panel.PanelDetailActivity
import com.itzyf.pokemondata.bean.DbPokemon
import com.itzyf.pokemondata.bean.RankDo
import com.itzyf.pokemondata.utils.OnRefreshListener
import com.itzyf.pokemondata.utils.setOnRefreshListener
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_list_filter2.*
import org.litepal.LitePal
import java.util.*
import kotlin.math.roundToInt


/**
 * @author 依风听雨
 * @version 创建时间：2019/01/09 09:13
 */
class RankSpeedReviseActivity : BaseActivity() {
    var mDatas: MutableList<RankDo?> = ArrayList()
    var index = 0
    private lateinit var mAdapter: QuickAdapter
    private var queryProperty = ""
    private lateinit var propertyList: Array<String>
    private var isStar = false
    private val fixedValue = 100 + 800 + 2028

    override fun handlerActivity() {
        propertyList = resources.getStringArray(R.array.propertyList)
        mAdapter = QuickAdapter(R.layout.item_speed, mDatas)
        rv_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        rv_list.adapter = mAdapter
//        showProgressDialog()
        queryDatas()

        mAdapter.setOnLoadMoreListener({ queryDatas(index++) }, rv_list)

        pull_to_refresh.setOnRefreshListener(object : OnRefreshListener {
            override fun onRefresh() {
                index = 0
                queryDatas(index)
            }
        })

        mBtnSearch.setOnClickListener {
            val query = mSearchView.text.toString()
            queryDatas(query = query)
        }
        mSearchView.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val query = mSearchView.text.toString()
                queryDatas(query = query)
                return@OnEditorActionListener true
            }
            false
        })

        spProperty.setItems(propertyList.toList())
        spProperty.setOnItemSelectedListener { _, position, _, _ ->
            queryProperty = when (position) {
                1 -> "普"
                2 -> "格"
                3 -> "飞"
                5 -> "地"
                6 -> "岩"
                8 -> "鬼"
                14 -> "超"
                18 -> "妖"
                0 -> ""
                else -> propertyList[position]
            }
            index = 0
            queryDatas(index)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this@RankSpeedReviseActivity, PanelDetailActivity::class.java)
            intent.putExtra("objId", mDatas[position]?.objectId)
            startActivity(intent)
        }
        ivStar.visibility = View.VISIBLE
        ivStar.setOnClickListener {
            isStar = !isStar
            ivStar.setImageResource(if (isStar) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp)
            index = 0
            queryDatas(index)
        }
    }

    override fun getContentViewId() = R.layout.activity_list_filter2

    override fun getToolbarTitle() = "速度排行榜-修正版"
    /**
     * 查询数据
     */
    fun queryDatas(index: Int = 0, pageSize: Int = 50, query: String = "") {
        var where = ""

        if (!TextUtils.isEmpty(query)) {
            where = "pokemonName like '%$query%'"
        }
        //属性筛选
        if (!TextUtils.isEmpty(queryProperty)) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where += "property like '%$queryProperty%'"
        }
        if (isStar) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where = "isStar = 1"
        }

        val dataList =
            LitePal
                .select("pokemonName", "objectId", "speed", "exclusiveId", "isLevel", "red1")
                .limit(pageSize)
                .offset(index * pageSize)
                .order("speed desc")
                .where(where)
                .find(DbPokemon::class.java)
        if (index == 0) {
            mDatas.clear()
            pull_to_refresh.finishRefresh()
        }

        for (obj in dataList) {
            val o = RankDo()
            o.objectId = obj.objectId
            o.pokemon = obj.pokemonName
            o.isLevel = obj.isLevel

            val split = obj.red1.split(",")
            if (split.size == 6) {
                obj.speed += split[5].toInt()
            }

            o.value = (obj.speed * 1.1).roundToInt() + fixedValue
            mDatas.add(o)

            if (!obj.exclusiveId.isNullOrEmpty()) {
                val o1 = RankDo()
                when (obj.exclusiveId) {
                    "5c4077cd128fe1002d250971" -> {
                        o1.pokemon = obj.pokemonName + "-裂空之粉"
                        o1.value = (obj.speed * 1.1 * 1.2).roundToInt() + fixedValue
                    }
                    "5c4077cd128fe1002d250979" -> {
                        o1.pokemon = obj.pokemonName + "-烈火印章"
                        o1.value = (obj.speed * 1.1 * 1.04).roundToInt() + fixedValue
                    }
                    "5c4077cd128fe1002d250982" -> {
                        o1.pokemon = obj.pokemonName + "-壮健大鳄"
                        o1.value = (obj.speed * 1.1 * 1.04).roundToInt() + fixedValue
                    }
                    "5c4077cd128fe1002d25098b" -> {
                        o1.pokemon = obj.pokemonName + "-尖锐尾棘"
                        o1.value = (obj.speed * 1.1 * 1.04).roundToInt() + fixedValue
                    }
                }
                if (o1.pokemon.isNotEmpty()) {
                    o1.objectId = obj.objectId
                    o1.isLevel = obj.isLevel
                    mDatas.add(o1)
                }
            }
        }

        mDatas.sortByDescending { it?.value }

        if (dataList.size < pageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
        mAdapter.notifyDataSetChanged()

    }


    internal inner class QuickAdapter(layoutResId: Int, data: List<RankDo?>) :
        BaseQuickAdapter<RankDo, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: RankDo?) {
            helper.setText(R.id.name, item?.pokemon)
            helper.setText(R.id.value, "${item?.value}")
            helper.setGone(R.id.ivUpdate, !item!!.isLevel)
        }
    }

}